<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-row>
            <el-col>
                <el-button type="primary" @click="addRoles">添加角色</el-button>
            </el-col>
        </el-row>
        <el-table :data="rolesList" border stripe>
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :index="i1" :class="['bBottm', i1 === 0 ? 'bTop' : '','vCenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                        <el-col :span="5"><el-tag closable @close="deleteRolesRight(scope.row,item1.id)">{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                        <el-col :span="19">
                            <el-row :index="i2" :class="['bTop', i2 === 2 ? '' : 'bTop','vCenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                <el-col :span="6"><el-tag type="success" closable @close="deleteRolesRight(scope.row,item2.id)">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                                <el-col :span="18"><el-tag :index="i3" v-for="(item3, i3) in item2.children" :key="item3.id" type="warning" closable @close="deleteRolesRight(scope.row,item3.id)">{{item3.authName}}</el-tag></el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column  label="角色名称" prop="roleName"></el-table-column>
            <el-table-column  label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column  label="操作" width="300px">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRole(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRolesDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <el-dialog
  title="分配权限"
  :visible.sync="RolesDialogVisible"
  width="50%"
  @close="closeTreeRolesList"
  >
  <el-tree :data="treeRolesList" :props="rolesProps" node-key="id" show-checkbox default-expand-all :default-checked-keys="defaultCheckedList" ref="treeRolesList"></el-tree>
  <span slot="footer">
    <el-button @click="RolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAssignPrivileges">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="添加新角色"
  :visible.sync="addRolesDialogVisible"
  width="50%"
  @close="closeAddRolesDialog"
  >
  <el-form :model="addRolesInfo" :rules="addRolesRules" ref="addRolesRef" label-width="100px" class="demo-ruleForm">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="addRolesInfo.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="addRolesInfo.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="subAddRolesInfo">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改角色信息"
  :visible.sync="editRolesInfoDialogVisible"
  width="50%"
  @close="closeEditRolesDialog"
  >
  <el-form :model="editRolesInfoList" :rules="addRolesRules" ref="editRolesRef" label-width="100px" class="demo-ruleForm">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="editRolesInfoList.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editRolesInfoList.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editRolesInfoDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="subEditRolesInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  name: 'roles',
  data () {
    return {
      rolesList: [],
      RolesDialogVisible: false,
      treeRolesList: [],
      rolesProps: {
        children: 'children',
        label: 'authName'
      },
      defaultCheckedList: [],
      rolesID: '',
      addRolesDialogVisible: false,
      addRolesInfo: {
        roleName: '',
        roleDesc: ''
      },
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称在2-10位之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 6, max: 20, message: '角色描述在6-24位之间', trigger: 'blur' }
        ]
      },
      editRolesInfoDialogVisible: false,
      editRolesInfoList: {}
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    async deleteRolesRight (role, roleId) {
      const userResponse = await this.$confirm('此操作将会删除该用户此权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (userResponse !== 'confirm') return this.$message.info('您取消了操作')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${roleId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      //   console.log(res)
      role.children = res.data
    },
    async showRolesDialog (role) {
      this.RolesDialogVisible = true
      this.rolesId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      //   console.log(res)
      if (res.meta.status !== 200) return
      this.treeRolesList = res.data
      //   console.log(this.treeRolesList)
      //   this.$refs.treeRolesList
      this.getLeafkeys(role, this.defaultCheckedList)
    },
    // 递归函数得出默认已经选好的
    getLeafkeys (node, array) {
      if (!node.children) {
        return array.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafkeys(item, array)
      })
    },
    closeTreeRolesList () {
      this.defaultCheckedList = []
    },
    async submitAssignPrivileges () {
      const checkedRoles = [
        ...this.$refs.treeRolesList.getCheckedKeys(),
        ...this.$refs.treeRolesList.getHalfCheckedKeys()
      ]
      const idStr = checkedRoles.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return
      this.$message.success('修改权限成功')
      this.RolesDialogVisible = false
      this.getRolesList()
    },
    addRoles () {
      this.addRolesDialogVisible = true
    },
    closeAddRolesDialog () {
      // console.log(2222)
      this.$refs.addRolesRef.resetFields()
    },
    subAddRolesInfo () {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', {
          roleName: this.addRolesInfo.roleName,
          roleDesc: this.addRolesInfo.roleDesc
        })
        if (res.meta.status !== 201) return this.$message.error('创建角色失败')
        this.$message.success(res.meta.msg)
        this.getRolesList()
      })
      this.addRolesDialogVisible = false
    },
    async showEditRoleDialog (id) {
      this.editRolesInfoDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRolesInfoList = res.data
      console.log(this.editRolesInfoList)
    },
    closeEditRolesDialog () {
      this.$refs.editRolesRef.resetFields()
    },
    subEditRolesInfo () {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`roles/${this.editRolesInfoList.roleId}`, {
          roleName: this.editRolesInfoList.roleName,
          roleDesc: this.editRolesInfoList.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('更新角色成功')
        this.getRolesList()
      })
      this.editRolesInfoDialogVisible = false
    },
    async delRole (id) {
      const userDeleteResponse = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (userDeleteResponse !== 'confirm') this.$message.info('您取消了删除操作')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>
<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bBottm{
    border-bottom: 1px solid #eee;
}
.bTop{
    border-top: 1px solid #eee;
}
.vCenter{
    display: flex;
    align-items: center;
}
</style>
